<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useGetReferPriceList } from '@fl/api/purchase'
import { SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const props = defineProps<{
    priceItemData: any
}>()
const emit = defineEmits<{
    insert: [price: number]
}>()
const visible = defineModel<boolean>('visible', { required: true })
const dialogTitle = '材料价目表'

const getReferPriceListParams = computed(() => ({
    cbCategoryId: props.priceItemData?.cbCategoryId,
    itemId: props.priceItemData?.itemId,
    modelId: props.priceItemData?.modelId,
}))

const { data: referPriceListData, isLoading: isGetReferPriceListLoading } = useGetReferPriceList(getReferPriceListParams)

// #region Table
const isTableLoading = computed(() => isGetReferPriceListLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'itemName', title: '产品名称' },
        { field: 'model', title: '规格型号' },
        { field: 'unit', title: '计量单位' },
        { field: 'price', title: '不含税价格' },
        { field: 'includeTaxPrice', title: '含税价格' },
        { slots: { default: 'operation' }, title: '操作', width: 100 },
    ],
    headerRowClassName: 'text-[#86909C] text-[14px]',
    height: undefined,
})
// #endregion

// #region UI Listener
function onInsertBtnClick(row: any) {
    emit('insert', row.price)
    cancel()
}

function cancel() {
    visible.value = false
}

function closed() {

}
// #endregion

watchEffect(() => {
    tableData.value = cloneDeep(referPriceListData.value) || []
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                close-on-press-escape
                width="1300"
                :has-footer="false"
                @cancel="cancel"
                @closed="closed"
    >
        <div class="h-620">
            <SearchTable v-bind="gridOptions"
                         :loading="isTableLoading"
                         :data="tableData"
            >
                <template #operation="{ row }">
                    <el-button text
                               class="!p-4"
                               type="primary"
                               @click="onInsertBtnClick(row)"
                    >
                        插入
                    </el-button>
                </template>
            </SearchTable>
        </div>
    </PlusDialog>
</template>

<style scoped lang="scss">
:deep(.vxe-table--body-wrapper) {
    min-height: 48px !important;
    max-height: 572px !important;
}
:deep(.vxe-grid--toolbar-wrapper) {
    display: none;
}
</style>
